package com.geline.mybatisplus.context;

import cn.hutool.core.thread.ThreadUtil;
import com.geline.mybatisplus.domain.ExtractEntity;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于保存@ExtractKey, @ExtractAfter 注解的参数
 *
 * @author mx
 * @date 2025/8/27
 */
public class ExtractTableThreadLocal {
    private ThreadLocal<Map<String, ExtractEntity>> extractTableLocal = ThreadUtil.createThreadLocal(false);

    /**
     * 设置参数
     * @param targetTable
     * @param idValue
     * @param entity 实体
     * @param childTable 子表
     */
    public void set(String targetTable, Serializable idValue, Object entity, String childTable) {
        Map<String, ExtractEntity> bean = extractTableLocal.get();
        if (bean == null) {
            bean = new HashMap<>();
        }
        String key = targetTable + ":" + idValue;
        if(bean.get(key)==null){
            ExtractEntity extractEntity = new ExtractEntity();
            extractEntity.setEntity(entity);
            extractEntity.setSourceTable(childTable);
            bean.put(key, extractEntity);
            extractTableLocal.set(bean);
        }
    }

    public Map<String, ExtractEntity> getMap() {
        return extractTableLocal.get();
    }

    public ExtractEntity getValue(String targetTable, Serializable idValue) {
        Map<String, ExtractEntity> map = getMap();
        if(map==null){
            return null;
        }
        String key = targetTable + ":" + idValue;
        return map.get(key);
    }

    public void remove() {
        extractTableLocal.remove();
    }
}
